from django.db import models
from users.models import User

class AIModel(models.Model):
    """AI模型选项"""
    name = models.CharField(max_length=100, verbose_name="模型名称")
    is_active = models.BooleanField(default=True, verbose_name="是否激活")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "AI模型"
        verbose_name_plural = "AI模型"

    def __str__(self):
        return self.name


class Tag(models.Model):
    """标签模型"""
    name = models.CharField(max_length=50, verbose_name="标签名称")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tags", verbose_name="创建用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = "标签"
        unique_together = ['name', 'user']

    def __str__(self):
        return self.name


class Prompt(models.Model):
    """提示词模型"""
    title = models.CharField(max_length=200, verbose_name="标题")
    content = models.TextField(verbose_name="提示词内容")
    version = models.CharField(max_length=50, default="1.0", verbose_name="版本")
    ai_output = models.TextField(blank=True, null=True, verbose_name="AI生成的内容")
    notes = models.TextField(blank=True, null=True, verbose_name="备注")
    is_public = models.BooleanField(default=True, verbose_name="是否公开")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="prompts", verbose_name="创建用户")
    ai_models = models.ManyToManyField(AIModel, related_name="prompts", verbose_name="适用模型")
    tags = models.ManyToManyField(Tag, blank=True, related_name="prompts", verbose_name="标签")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "提示词"
        verbose_name_plural = "提示词"
        ordering = ['-updated_at']

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        # 检查是否是新创建的提示词
        is_new = self.pk is None
        
        # 保存提示词
        super().save(*args, **kwargs)
        
        # 如果是新创建的提示词，更新用户的提示词计数
        if is_new and self.user:
            self.user.prompt_count += 1
            self.user.save(update_fields=['prompt_count'])


class PromptVersion(models.Model):
    """提示词版本历史"""
    prompt = models.ForeignKey(Prompt, on_delete=models.CASCADE, related_name="versions", verbose_name="提示词")
    version = models.CharField(max_length=50, verbose_name="版本号")
    content = models.TextField(verbose_name="内容")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "提示词版本"
        verbose_name_plural = "提示词版本"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.prompt.title} - {self.version}"
